package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//接收请求
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet{

    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User(null,username,password);
        //转发到service
        User _user = userService.findByNameAndPwd(user);
        //map  flag  true|false true代表成功 false失败
        //     message   失败 失败的错误信息
        Map map = new HashMap<>();
        if(_user==null){
            //用户名或密码输入错误
            map.put("flag",false);
            map.put("message","用户名或密码输入错误");
        }else{
            map.put("flag",true);
            //用户名或密码输入正确
            req.getSession().setAttribute("username",user.getUsername());
        }
        //将map转成json发送到前端 {"flag":true|fasle,"message":xxx}
          ObjectMapper mapper= new ObjectMapper();
        String rst = mapper.writeValueAsString(map);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(rst);
    }
}
